package org.binge.widget.web.controller;

import com.alibaba.fastjson.JSON;
import org.binge.widget.facade.BpFileService;
import org.binge.widget.facade.ParserExcelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by lurongyu on 16-3-14.
 */
@Controller
@RequestMapping("/dealFile")
public class FileAction extends HttpServlet {

    public static final String CONTRACT_FTP_PATH = "CONTRACT_FTP_PATH";
    public static final int FILE_CONTRACT = 1;
    private static Logger logger = LoggerFactory.getLogger(FileAction.class);

    @Autowired
    private BpFileService bpFileService;

    @Autowired
    private ParserExcelService parserExcelService;

    private static final String IMPORT_FTP_PATH = "IMPORT_FTP_PATH";

    private static final int insertCount = 100;//一次入表的条数(查询该条数后,调用入表服务操作)


    @RequestMapping(value = "/uploadFileToFTP", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String uploadFileToFTP(@RequestParam("folderName") String folderName, HttpServletRequest request) {
        //请求具体处理
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        Map resultMap = new HashMap();
        InputStream is2 = null;
        FileOutputStream fos = null;

        MultipartFile file = mRequest.getFile("flowFile");
        String originalFileName = file.getOriginalFilename();
        String type = originalFileName.substring(originalFileName.lastIndexOf("."));// 取文件格式后缀名
        String newFileName = originalFileName.substring(0, originalFileName.length() - type.length()) + System.currentTimeMillis() + type;//拼接新名字

        try{
            long fileId = parserExcelService.createSequenceFileId("BP_FILE_SEQ");
            //返回前台信息
            resultMap.put("fileId", fileId);
            resultMap.put("originalFileName", originalFileName);
            resultMap.put("newFileName", newFileName);
            resultMap.put("remotePath", "/var/tmp");

            resultMap.put("success", true);
            resultMap.put("message", originalFileName + "上传成功");

            is2 = file.getInputStream();
            fos = new FileOutputStream("/var/tmp/" + newFileName);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is2.read(buffer)) != -1) {
                fos.write(buffer);
            }

        } catch (Exception e) {
            resultMap.put("message", originalFileName + "上传失败");
        } finally {
            try {
                if (is2 != null) {
                    is2.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return JSON.toJSON(resultMap).toString();
    }

    @RequestMapping(value = "/recordBpFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> recordBpFile(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap();
        try {
            //获取前台信息
            String templateCode = request.getParameter("templateCode");
            long fileId = Long.valueOf(request.getParameter("fileId"));
            long dataId = fileId;           //设置dataId于fileId相同
            String originalFileName = request.getParameter("originalFileName");
            String newFileName = request.getParameter("newFileName");
            //其他入库所需信息
            long opId = 1L;
            long orgId = 1L;
            String regionId = "reg0";
            String state = (String) "U";
            Integer priority = (int) 5;
            String keyData = (String) "银行流水导入";
            String statusNotify = (String) "待定-状态通知";
            //入Bp_File Bp_Data表信息(设置dataId时,设置其等于fileId)
            Map fileMap = new HashMap();
            fileMap.put("fileId", fileId);
            fileMap.put("dataId", dataId);
            fileMap.put("originalFileName", originalFileName);
            fileMap.put("newFileName", newFileName);

            fileMap.put("opId", opId);
            fileMap.put("orgId", orgId);//临时
            fileMap.put("regionId", regionId);
            fileMap.put("templateCode", templateCode);
            fileMap.put("state", state);
            fileMap.put("priority", priority);
            fileMap.put("keyData", keyData);
            fileMap.put("statusNotify", statusNotify);
            bpFileService.insertFileAndData(fileMap);

            //返回前台信息
            resultMap.put("success", true);
        } catch (Exception e) {
            resultMap.put("message", "记录文件上传信息失败");
            e.printStackTrace();
        }
        return resultMap;
    }


    @RequestMapping("/parserFileAndInsertDB")
    @ResponseBody
    public String parserFileAndInsertDB(HttpServletRequest request) {
        Map resultMap = new HashMap();
        try {
            //获取前台信息
            String templateCode = request.getParameter("templateCode");
            long fileId = Long.parseLong(request.getParameter("fileId"));
            long dataId = fileId;           //设置dataId于fileId相同
            String newFileName = request.getParameter("newFileName");
            String originalFileName = request.getParameter("originalFileName");
            String remotePath = request.getParameter("remotePath");
            remotePath = "/var/tmp";
            //入库操作所需文件附属信息
            long opId = Long.valueOf(1);
            long orgId = Long.valueOf(1);
            String regionId = "reg0";
            String state = (String) "U";
            Integer priority = (int) 5;
            String keyData = (String) "银行流水导入";
            String statusNotify = (String) "待定-状态通知";


            //解析及入库(考虑大容量文件,解析入库操作分段进行)
            Map fileMap = new HashMap();//存放入库文件附属信息
            fileMap.put("fileId", fileId);
            fileMap.put("dataId", dataId);
            fileMap.put("originalFileName", originalFileName);
            fileMap.put("newFileName", newFileName);
            fileMap.put("opId", opId);//临时
            fileMap.put("orgId", orgId);//临时
            fileMap.put("regionId", regionId);
            fileMap.put("templateCode", templateCode);
            fileMap.put("state", state);
            fileMap.put("priority", priority);
            fileMap.put("keyData", keyData);
            fileMap.put("statusNotify", statusNotify);
            //解析入库操作入口
            String message = "";//回送信息
            String type = originalFileName.substring(originalFileName.lastIndexOf("."));// 取文件格式后缀名
            if (".xls".equalsIgnoreCase(type) || ".xlsx".equalsIgnoreCase(type)) {
                //进行excel解析
                parserExcelService.ParseExcelFile(remotePath + File.separator + newFileName, fileMap);
                message = "文件解析入库完成！";
            } else if ("txt".equalsIgnoreCase(type)) {
                //进行txt解析

                message = "文件解析入库完成！";
            } else {
                //报不可解析，文件类型不支持错误
                message = "文件类型或文件内容格式不支持，解析入库失败！";
            }

            resultMap.put("fileId", fileId);

            resultMap.put("message", message);
            resultMap.put("success", true);
        } catch (Exception e) {
            resultMap.put("message", "文件解析入库失败");
            e.printStackTrace();
        }
        return JSON.toJSON(resultMap).toString();
    }

    @RequestMapping(value = "/getInitHead", method = RequestMethod.POST)
    @ResponseBody
    public String getInitHead(@RequestParam("fileId") Long fileId) {
        List headList = new ArrayList();
        try {
            headList = bpFileService.getInitHead(fileId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSON(headList).toString();
    }

    @RequestMapping(value = "/getInitData", method = RequestMethod.POST)
    @ResponseBody
    public String getInitData(@RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer rows, HttpServletRequest request) {
        Map resultMap = new HashMap();
        try {
            Long fileId = Long.parseLong(request.getParameter("fileId"));//文件入库fileId
            int totalData = bpFileService.selectSuccessCount(fileId) - 1;//减去表头行
            Integer start = (page - 1) * rows;
            List dataList = bpFileService.selectBpFileAndDataPager(start, rows, fileId);
            resultMap.put("rows", dataList);
            resultMap.put("total", totalData);
            resultMap.put("message", "原始数据查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("message", "原始数据查询失败");
        }
        return JSON.toJSON(resultMap).toString();
    }

}
